﻿using System;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;
using gtasks.Auth;
using gtasks.Model;
using gtasks.Model.Convert;
using pub.GUI;
using pub.NET20Fix;
using pub.Types;
using todo;
using todo.Model;
using todo.Persistence;

namespace gtasks
{
    internal partial class OpenTasklistForm : Form
    {
        public string FileName { get; set; }
        public TodoList TodoList { get; set; }
        public volatile bool Canceled;

        private string _taskListTitle;
        private int _progressCounter;
        private string _progressStatus;

        public OpenTasklistForm()
        {
            InitializeComponent();
            this.Font = SystemFonts.DialogFont;
            Canceled = true;
#if zh
            this.Text = "Google 任务";
#endif
        }

        private void OpenTasklistForm_Shown(object sender, EventArgs e)
        {
            AuthManager.Instance.OnException += AuthManager_OnException;
            TaskListManager.Instance.OnException += TaskListManager_OnException;
            CheckUpdate();
        }

        void AuthManager_OnException(Exception e)
        {
            App.OnUnknownException(e);
            this.Close();
        }

        void TaskListManager_OnException(Exception e)
        {
            App.OnUnknownException(e);
            this.Close();
        }

        private void CheckUpdate()
        {
//            lblProgress.Text = "Checking update..";
            var pos1 = FileName.IndexOf(')') + 1;
            var pos2 = FileName.LastIndexOf('.');
            _taskListTitle = FileName.Substring(pos1, pos2 - pos1);
            _progressStatus = "Opening";
#if zh
            _progressStatus = "正在打开";
#endif

            var taskListId = TodoList.Id;
            TaskListManager.Instance.Get(taskListId, taskList => {
                Debug.Print("@@@@@@@@@@@@@@ TaskListManager.Instance.Get returns @ " + DateTime.Now);
                var updateTime = taskList.updated;
                if (Math.Abs((updateTime - TodoList.UpdateTime).TotalSeconds) >= 1)
                {
                    Dispatcher.Current.Invoke(() => PromptUpdate(taskList));
                }
                else
                {
                    Canceled = false;
                    Dispatcher.Current.Invoke(Close);
                }
            });
        }

        private void PromptUpdate(TaskList taskList)
        {
            var msg = "Local todolist is outdated, do you want to update it now?";
#if zh
            msg = "本地的待办列表已过时，立即下载更新吗?";
#endif
            var dr = MessageBox.Show(FormUtils.GetLastForm(), msg, "Google tasks",
                    MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
            if (dr != DialogResult.Yes)
            {
                Canceled = dr == DialogResult.Cancel;
                this.Close();
                return;
            }
            _progressStatus = "Downloading";
#if zh
            _progressStatus = "正在下载";
#endif

            TaskManager.Instance.LoadTasks(TodoList.Id, tasks => {
                var todolist = TaskListToTodoList.Convert(taskList, tasks);
                TodoListWriter.Save(todolist, FileName);
                Canceled = false;
                Dispatcher.Current.Invoke(Close);
            });
        }

        private void timerOpening_Tick(object sender, EventArgs e)
        {
            var text = _progressStatus + ' ' + _taskListTitle + ' ';
            text += new string('.', (++_progressCounter%3) + 1);
            lblTitle.Text = text;
        }

        private void OpenTasklistForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            TaskListManager.Instance.OnException -= TaskListManager_OnException;
            AuthManager.Instance.OnException -= AuthManager_OnException;
            if (Canceled)
            {
                TaskListManager.Instance.AbortProcessing();
            }
        }
    }
}